package io.afu.baseframework.annotations.impls;

import io.afu.baseframework.annotations.Upper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

@Aspect
@Component
public class MustUpperImpl {

    private Logger logger = LoggerFactory.getLogger(getClass());



    @Pointcut(value = "@annotation(io.afu.baseframework.annotations.MustUpper)")
    public void cutMustUpper(){

    }


    @Around("cutMustUpper()")
    public Object resetToUpperCase(ProceedingJoinPoint point) throws Throwable {
        //先执行业务
        logger.info("进入了这个切面");
        try {
            Object[] args = point.getArgs();
            for (Object param:args){
                Class c = param.getClass();
                // 获取里面的所有属性
                Field[] fields = c.getDeclaredFields();
                for (Field field:fields){
                    // 判断属性是否包含Upper注解
                    if (field.isAnnotationPresent(Upper.class)){
                        // 设置属性可见
                        field.setAccessible(true);
                        // 获取属性值
                        Object value = field.get(param);
                        if (value != null){
                            // 将属性值转换为大写
                            try {
                                String upperValue = value.toString().toUpperCase();
                                // 将属性值重新设置
                                field.set(param,upperValue);
                            }catch (Exception e){
                                e.printStackTrace();
                            }
                        }
                    }

                }
            }

            Object target  = point.getTarget();
            logger.info(target.toString());
        } catch (Exception e) {
            logger.error("日志记录出错!", e);
        }
        Object result = point.proceed();
        return result;
    }










}
